package selef.xiafan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import selef.xiafan.dao.*;
import selef.xiafan.entity.CommentOrder;
import selef.xiafan.entity.system.Category;
import selef.xiafan.entity.Customer;
import selef.xiafan.entity.order.Order;
import selef.xiafan.entity.order.OrderCategory;
import selef.xiafan.entity.order.OrderCustomer;
import selef.xiafan.query.OrderQ;
import selef.xiafan.service.IOrderService;
import selef.xiafan.util.result.PageResult;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IOrderServiceImpl implements IOrderService {
    @Autowired
    OrderDao orderDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CustomerDao customerDao;
    @Autowired
    OrderCustomerDao orderCustomerDao;
    @Autowired
    OrderCategoryDao orderCategoryDao;
    @Autowired
    CommentOrderDao commentOrderDao;


    @Override
    public PageResult<Order> orderList(OrderQ orderQ) {
        Integer page = (orderQ.getPage() - 1) * orderQ.getSize();
        Integer size = orderQ.getSize();
        String customerName = orderQ.getCustomerName();
        Integer status = orderQ.getStatus();


        // 刷新页面或者不带参数查询时
        if ("".equals(customerName) && status == null) {
            Long total = orderDao.countAll();
            if (total == 0L) {
                return new PageResult<>();
            }
            List<Order> orderList = orderDao.findAllNoQuery(page, size);
            Iterator<Order> iterator = orderList.iterator();
            while (iterator.hasNext()) {
                Order order = iterator.next();
                Integer customerId = orderCustomerDao.findByOrderId(order.getOrderId()).getCustomerId();
                Customer customerAdd = customerDao.findById(customerId).get();
                order.setCustomer(customerAdd);
                List<Integer> categoryId = orderCategoryDao.findAllByOrderId(order.getOrderId())
                        .stream().map(OrderCategory::getCategoryId).collect(Collectors.toList());
                List<Category> categoryAdd = categoryDao.findAllById(categoryId);
                order.setCategory(categoryAdd);
            }
            return new PageResult<>(total, orderList);
        }
        // 根据名字查询用户，根据用户id查询订单
//        List<Customer> customerDByName = customerDao.findByName(customerName);
        List<Customer> customerDByName = customerDao.findAllByQuery(customerName);
        List<Order> orderList = new ArrayList<>();
        for (Customer customer : customerDByName) {
            Order withQuery = null;
            if (status != null) {
                withQuery = orderDao.findWithQuery(page, size, customer.getId(), status);
            } else {
                withQuery = orderDao.findWithQueryNoStatus(page, size, customer.getId());
            }

            // begin 查询订单时可能存在订单删除后用户信息没有删除，导致订单查询为空
            if (withQuery != null) {
                // end
                Integer customerId = orderCustomerDao.findByOrderId(withQuery.getOrderId()).getCustomerId();
                Customer customerUpdate = customerDao.findById(customerId).get();
                withQuery.setCustomer(customerUpdate);

                List<Integer> categoryId = orderCategoryDao.findAllByOrderId(withQuery.getOrderId())
                        .stream().map(OrderCategory::getCategoryId).collect(Collectors.toList());
                List<Category> categoryAdd = categoryDao.findAllById(categoryId);
                withQuery.setCategory(categoryAdd);

                orderList.add(withQuery);
            }

        }
        int size1 = customerDByName.size();
        long total = (int) size1;
        return new PageResult<>(total, orderList);
    }

    @Override
    public PageResult<Order> customerOrderList(OrderQ orderQ) {
        Integer page = (orderQ.getPage() - 1) * orderQ.getSize();
        Integer size = orderQ.getSize();
        String createBy = String.valueOf(orderQ.getId()); // 用户id，不是客户id
        if (createBy != null) {
//            Order withQuery = orderDao.findWithQuery(page, size, createBy);
            List<Order> withQuery = orderDao.findAllWithQuery(page, size, createBy);
            for (Order order : withQuery) {
                Integer customerId = orderCustomerDao.findByOrderId(order.getOrderId()).getCustomerId();
                Customer customer = customerDao.findById(customerId).get();
                order.setCustomer(customer);
                List<Integer> categoryId = orderCategoryDao.findAllByOrderId(order.getOrderId())
                        .stream().map(OrderCategory::getCategoryId).collect(Collectors.toList());
                List<Category> categoryAdd = categoryDao.findAllById(categoryId);
                order.setCategory(categoryAdd);
                // 查评论
                CommentOrder byOrderId = commentOrderDao.findByOrderId(order.getOrderId());
                // 已经评论
                if (byOrderId != null) {
                    order.setIsComment(0);
                    // 还没评论
                } else {
                    order.setIsComment(1);
                }
            }
            return new PageResult<>((long) withQuery.size(), withQuery);

            /*Integer customerId = orderCustomerDao.findByOrderId(withQuery.getOrderId()).getCustomerId();
            Customer customerUpdate = customerDao.findById(customerId).get();
            withQuery.setCustomer(customerUpdate);

            List<Integer> categoryId = orderCategoryDao.findAllByOrderId(withQuery.getOrderId())
                    .stream().map(OrderCategory::getCategoryId).collect(Collectors.toList());
            List<Category> categoryAdd = categoryDao.findAllById(categoryId);
            withQuery.setCategory(categoryAdd);
            orderList.add(withQuery);
            return new PageResult<>((long)orderList.size(),orderList);*/
        } else {
            return null;
        }

    }

    @Override
    @Transactional
    public Integer addOrUpdate(Order order) {
        // 先查询数据库，以是否有数据作为添加或修改的依据
        Order byOrderId = orderDao.findByOrderId(order.getOrderId());
        // 添加
        if (byOrderId == null) {
            Customer customerFromOrder = order.getCustomer();
            List<Customer> customerByPhone = customerDao.findAllByPhone(customerFromOrder.getPhone());
            Boolean isVip = false;
            customerFromOrder.setIsVip(isVip);
            if (customerByPhone.size() != 0) {
                for (Customer customer : customerByPhone) {
                    // 相同的客户更新数据
                    if (customer.getName().equals(customerFromOrder.getName()) && customer.getPhone().equals(customerFromOrder.getPhone()) && customer.getCarNum().equals(customerFromOrder.getCarNum())) {
                        customerFromOrder.setId(customer.getId());
                        customerFromOrder.setAddress(order.getAddress());
                        customerFromOrder.setIsVip(customer.getIsVip());
                    }
                }
            }
            // 第一次添加订单--客户直接保存
            customerDao.save(customerFromOrder);
            // 添加了客户之后再进行查询，得到信息用户保存中间表
//            List<Customer> customerDByName = customerDao.findByName(order.getCustomer().getName());
//            customerDByName.forEach(customer -> {
//                if (customer.getId().equals(order.getCustomer().getId())) {
            OrderCustomer orderCustomer = new OrderCustomer();
            orderCustomer.setOrderId(order.getOrderId());
            orderCustomer.setCustomerId(customerFromOrder.getId());
            orderCustomerDao.save(orderCustomer);
//                }
//            });
            // 根据服务类型存储中间表+
            order.getCategory().forEach(category -> {
                OrderCategory orderCategory = new OrderCategory();
                orderCategory.setOrderId(order.getOrderId());
                orderCategory.setCategoryId(category.getId());
                orderCategoryDao.save(orderCategory);
            });
            orderDao.save(order);
            return 1;
        }
        if (byOrderId != null) {
            // 更新客户地址
            customerDao.save(order.getCustomer());
            // 更新服务信息
            List<Category> categoryList = order.getCategory();
            if (categoryList.size() == 0) {
                // 如果取消了服务，删除记录的服务，没有意义
                String orderId = order.getOrderId();
                orderCategoryDao.deleteAllByOrderId(orderId);
            } else {
                categoryList.forEach(category -> {
                    OrderCategory orderCategory = new OrderCategory();
                    orderCategory.setOrderId(order.getOrderId());
                    orderCategory.setCategoryId(category.getId());
                    orderCategoryDao.save(orderCategory);
                });
            }
            orderDao.save(order);
            return 2;
        }
        return 3;
    }

    /**
     * 单个删除和批量删除
     */
    @Override
    @Transactional
    public Integer delete(Order order) {
        commonDelete(order);
        return 1;
    }

    @Override
    @Transactional
    public Integer batchDelete(List<Order> orderList) {
        for (Order order : orderList) {
            commonDelete(order);
        }
        return 1;
    }

    @Override
    public List<Order> getDayOrder() {
        List<Order> dayOrder = orderDao.getDayOrder();
        return dayOrder;
    }

    @Override
    public List<Order> getAll() {
        List<Order> all = orderDao.findAll();
        return all;
    }

//    @Override
//    public List<Order> queryWeekData() {
//        return orderDao.queryWeekData();
//    }

    public void commonDelete(Order order) {
        // 查询订单-类型表（t_order_category)表中有订单id的信息
        List<Integer> orderCategoryId = orderCategoryDao.findAllByOrderId(order.getOrderId())
                .stream().map(OrderCategory::getId).collect(Collectors.toList());

        // 根据订单id查询订单-客户信息
        Integer orderCustomerInDbId = orderCustomerDao.findByOrderId(order.getOrderId()).getId();
//        Integer id = orderCustomerInDb.getId();
//        Integer customerId = orderCustomerInDb.getCustomerId();

        if (orderCategoryId.size() != 0 && orderCustomerInDbId != null) {
            orderCategoryDao.deleteAllById(orderCategoryId);
            orderCustomerDao.deleteById(orderCustomerInDbId);
//            customerDao.deleteById(customerId);
            orderDao.deleteByOrderId(order.getOrderId());
        }
    }

    /*
     * 订单提交，改变状态，交给维修部
     * */
    @Override
    public Integer confirmOrder(Order order) {
        Integer status = order.getStatus();
        if (status == 1) {
            order.setStatus(2);
            orderDao.save(order);
            return 1;
        }
        if (status == 2) {
            return 2;
        }
        if (status == 3) {
            return 3;
        }
        if (status == 4) {
            return 4;
        }
        return 0;
    }

    @Override
    public PageResult<Order> orderItemList(OrderQ orderQ) {
        Integer page = (orderQ.getPage() - 1) * orderQ.getSize();
        Integer size = orderQ.getSize();

        Long total = orderDao.itemCountAll();
        if (total == 0L) {
            return new PageResult<>();
        }
        // 刷新页面或者不带参数查询时
        List<Order> orderList = orderDao.findAllItemOrder(page, size);
        Iterator<Order> iterator = orderList.iterator();
        while (iterator.hasNext()) {
            Order order = iterator.next();
            Integer customerId = orderCustomerDao.findByOrderId(order.getOrderId()).getCustomerId();
            Customer customerAdd = customerDao.findById(customerId).get();
            order.setCustomer(customerAdd);
            List<Integer> categoryId = orderCategoryDao.findAllByOrderId(order.getOrderId())
                    .stream().map(OrderCategory::getCategoryId).collect(Collectors.toList());
            List<Category> categoryAdd = categoryDao.findAllById(categoryId);
            order.setCategory(categoryAdd);
        }
        return new PageResult<>(total, orderList);
    }
}
